package hc.bre.calc.scorecard

import hc.bre.cmn.RuleDefinition
import hc.bre.cmn.RuleScriptBuilder
import hc.bre.func.FunctionDefinition
import hc.bre.func.FunctionItem
import hc.bre.policy.CategoryDefinition
import hc.bre.policy.CategoryOption
import hc.bre.policy.CheckResultReason
import hc.bre.policy.ReasonDefinition
import hc.bre.policy.ReasonItem
import hc.bre.project.ProjectDefinition
import net.bytebuddy.asm.Advice.This

@groovy.transform.CompileStatic
class ScBuilder extends RuleScriptBuilder<ScorecardDefinition>{
	@Override
	public Class buildClassRuleBodyResult_Class() {
		return ScResult.class;
	}

	@Override
	public void buildClassRuleBodyCore() {
		apdNl("${result}.score = ${ruleDef.score};" );

		apdNl("def _clasReturn_;");
		String scDetailItemName = className(ScResultDetailItem);
		ruleDef.list.each {ScBranchItem branch ->
			apdNl("_clasReturn_ = ${_applyClas(branch.referId)};");
			apdNl("switch(_clasReturn_.clas.id){");
			nested{
				branch.list.each { ScLeafItem leaf ->
					apdNl("case ${leaf.referId}: ");

					nested{
						apdNl("${result}.score += ${leaf.score};");
						apdNl("${result}.detail.add(new ${scDetailItemName}(")
								.apd("clas:_clasReturn_, ")
								.apd("score:${leaf.score}, ")
								.apd("reason:${_referReason(leaf.reasonId)}, ")
								.apd("userdef:${leaf.userdef?:'null'}));");
						apdNl("break;");
					};
				};

				apdNl("default : assert false;break;")
			}

			apdNl("};")
		}

		apdNl("${result}.score = ${_referTranform()}(${result}.score);")
	}

//	String _applyClas(int ruleId) {
//		"${referApplyRule(ruleId)}";
//	}
	
	String _applyClas(String rpath) {
		"${referApplyRule(rpath)}";
	}

	String _referReason(Integer reasonId) {
		routeOfRuleItem(ruleOfReason, reasonId)
	}

	String _referTranform() {
		routeOfRuleItem(rule(FunctionDefinition.class), ruleDef.transform, '')
	}
}